require 'rexml/document'

module OPML

  include REXML
  def OPML.parse(body,user)
    root =  Document.new(body).elements['opml/body']
    visit(root,-1,user)
  end

  def OPML.visit(element, category_id,user)
    element.elements.to_a.find_all{ |e| e.attributes["xmlUrl"].nil?}.each do |e|
      category = Category.create(:title => e.attributes['title'])
      visit(e, category.id,user)
    end

    element.elements.to_a.find_all{ |e| !e.attributes["xmlUrl"].nil?}.each do |e|
      feed = Feed.find_by_url(e.attributes['xmlUrl']) || Feed.create!(:url => e.attributes['xmlUrl'])
      feed.refresh
      feed.save!
      Subscription.subscribe(user,feed,category_id) unless user.has?(feed)
    end

  end
end
